#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper



node (params.nodeLabel) {
    def status = 0
    def tomcatHome = '/home/tomcat'
    def tomcatWebPath = tomcatHome + '/webapps'
    def bakPath = '/opt/app-bak'
    println(params.action)
   if('rollback'== params.action){
        rollBackForWar(tomcatWebPath,bakPath,tomcatHome)
    }else {
        println('No Action Not Found...')
    }
}

def notifyDeployCentral(status){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}@${params.nodeLabel}",timeout: 10)
        println('Status: '+response.status)
    }
}


def stopTomcat(){
    println("---- Stop Tomcat ----")
    def pid = sh(script: 'ps -ef | grep -w tomcat | grep -v grep | awk \'{print $2}\'',returnStdout: true).trim()
    echo 'Tomcat pid: '+ pid
    if(null != pid && "" != pid){
        sh "kill ${pid}"
    }
    sleep 5
}

def startTomcat(tomcatHome){
    println("---- startTomcat ----:"+tomcatHome)
    script{
        withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
            sh """
            ${tomcatHome}/bin/startup.sh
          """
        }
    }
}

def rollBackForWar(tomcatWebPath,bakPath,tomcatHome){
    try{
        stage('Stop Tomcat'){
            stopTomcat()
        }
        stage('RollBack Artifact') {
            sh """
               cp ${bakPath}/*.war ${tomcatWebPath}
             """
            sh "ls ${tomcatWebPath}"
        }
        stage('Start Tomcat'){
            startTomcat(tomcatHome)
            sleep 20
        }
        stage('Verify App'){
            def resp = httpRequest(url:"http://localhost:${params.appPort}${params.appCheckUrl}",timeout: 20)
            println('Status: '+resp.status)
        }
        notifyDeployCentral(18002) //回滚成功
    }catch (e){
        echo 'RollBackForWar Error !'
        notifyDeployCentral(18003) //回滚失败
        throw e
    }
}
